/**
 * 悬浮窗管理器
 * 负责管理桌面宠物的悬浮窗显示和App外显示功能
 */

class FloatingWindowManager {
  constructor() {
    this.isFloatingEnabled = false
    this.isAppBackground = false
    this.floatingWindow = null
    this.originalPetElement = null
    this.petData = null
    this.eventListeners = new Map()
    
    this.init()
  }
  
  /**
   * 初始化悬浮窗管理器
   */
  init() {
    try {
      // 检查是否支持悬浮窗权限
      this.checkFloatingPermission()
      
      // 监听App生命周期
      this.setupAppLifecycleListeners()
      
      console.log('悬浮窗管理器初始化成功')
    } catch (error) {
      console.error('悬浮窗管理器初始化失败:', error)
    }
  }
  
  /**
   * 检查悬浮窗权限
   */
  async checkFloatingPermission() {
    try {
      // 检查是否有悬浮窗权限
      if (typeof uni !== 'undefined' && uni.getSystemSetting) {
        const settings = await uni.getSystemSetting()
        this.isFloatingEnabled = settings.floatingWindow || false
      }
      
      // 检查设备是否支持悬浮窗
      const systemInfo = uni.getSystemInfoSync()
      const supportedPlatforms = ['android', 'ios']
      const isSupported = supportedPlatforms.includes(systemInfo.platform)
      
      if (!isSupported) {
        console.warn('当前平台不支持悬浮窗功能')
        this.isFloatingEnabled = false
      }
      
      return this.isFloatingEnabled
    } catch (error) {
      console.error('检查悬浮窗权限失败:', error)
      return false
    }
  }
  
  /**
   * 设置App生命周期监听
   */
  setupAppLifecycleListeners() {
    // 监听App进入后台
    uni.onAppHide(() => {
      this.isAppBackground = true
      this.handleAppBackground()
    })
    
    // 监听App进入前台
    uni.onAppShow(() => {
      this.isAppBackground = false
      this.handleAppForeground()
    })
  }
  
  /**
   * 处理App进入后台
   */
  handleAppBackground() {
    if (this.isFloatingEnabled && this.petData && this.petData.isActive) {
      // 创建悬浮窗
      this.createFloatingWindow()
    }
  }
  
  /**
   * 处理App进入前台
   */
  handleAppForeground() {
    if (this.floatingWindow) {
      // 销毁悬浮窗
      this.destroyFloatingWindow()
    }
  }
  
  /**
   * 创建悬浮窗
   */
  createFloatingWindow() {
    try {
      if (this.floatingWindow) {
        return // 已经存在悬浮窗
      }
      
      // 获取宠物元素
      this.originalPetElement = document.querySelector('.desktop-pet')
      if (!this.originalPetElement) {
        console.warn('未找到宠物元素')
        return
      }
      
      // 克隆宠物元素
      const clonedPet = this.originalPetElement.cloneNode(true)
      clonedPet.classList.add('floating-pet')
      
      // 创建悬浮窗容器
      this.floatingWindow = document.createElement('div')
      this.floatingWindow.className = 'floating-window-container'
      this.floatingWindow.appendChild(clonedPet)
      
      // 设置悬浮窗样式
      this.setupFloatingWindowStyles()
      
      // 添加到页面
      document.body.appendChild(this.floatingWindow)
      
      // 隐藏原始宠物
      this.originalPetElement.style.display = 'none'
      
      console.log('悬浮窗创建成功')
      this.emit('floating-window-created', this.floatingWindow)
      
    } catch (error) {
      console.error('创建悬浮窗失败:', error)
    }
  }
  
  /**
   * 设置悬浮窗样式
   */
  setupFloatingWindowStyles() {
    const style = document.createElement('style')
    style.textContent = `
      .floating-window-container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        pointer-events: none;
        z-index: 99999;
        background: transparent;
      }
      
      .floating-window-container .floating-pet {
        pointer-events: auto;
        position: fixed !important;
        z-index: 99999 !important;
      }
      
      .floating-window-container .floating-pet .pet-body {
        background: rgba(255, 255, 255, 0.95) !important;
        backdrop-filter: blur(10px);
        border: 2px solid rgba(102, 126, 234, 0.3);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2) !important;
      }
    `
    document.head.appendChild(style)
  }
  
  /**
   * 销毁悬浮窗
   */
  destroyFloatingWindow() {
    try {
      if (this.floatingWindow) {
        document.body.removeChild(this.floatingWindow)
        this.floatingWindow = null
      }
      
      // 显示原始宠物
      if (this.originalPetElement) {
        this.originalPetElement.style.display = 'block'
      }
      
      console.log('悬浮窗销毁成功')
      this.emit('floating-window-destroyed')
      
    } catch (error) {
      console.error('销毁悬浮窗失败:', error)
    }
  }
  
  /**
   * 启用悬浮窗功能
   */
  async enableFloatingWindow() {
    try {
      // 检查权限
      const hasPermission = await this.checkFloatingPermission()
      
      if (!hasPermission) {
        // 请求悬浮窗权限
        const granted = await this.requestFloatingPermission()
        if (!granted) {
          throw new Error('用户拒绝了悬浮窗权限')
        }
      }
      
      this.isFloatingEnabled = true
      
      // 保存设置
      uni.setStorageSync('floating_window_enabled', true)
      
      console.log('悬浮窗功能已启用')
      this.emit('floating-window-enabled')
      
      return true
    } catch (error) {
      console.error('启用悬浮窗失败:', error)
      this.emit('floating-window-error', error.message)
      return false
    }
  }
  
  /**
   * 禁用悬浮窗功能
   */
  disableFloatingWindow() {
    try {
      this.isFloatingEnabled = false
      
      // 如果存在悬浮窗，销毁它
      if (this.floatingWindow) {
        this.destroyFloatingWindow()
      }
      
      // 保存设置
      uni.setStorageSync('floating_window_enabled', false)
      
      console.log('悬浮窗功能已禁用')
      this.emit('floating-window-disabled')
      
    } catch (error) {
      console.error('禁用悬浮窗失败:', error)
    }
  }
  
  /**
   * 请求悬浮窗权限
   */
  async requestFloatingPermission() {
    return new Promise((resolve) => {
      uni.showModal({
        title: '悬浮窗权限',
        content: '需要悬浮窗权限来在App外显示桌面宠物，是否允许？',
        success: (res) => {
          if (res.confirm) {
            // 在真实环境中，这里应该调用系统API请求权限
            // 由于uni-app的限制，这里只是模拟
            resolve(true)
          } else {
            resolve(false)
          }
        }
      })
    })
  }
  
  /**
   * 更新宠物数据
   */
  updatePetData(petData) {
    this.petData = petData
    
    // 如果悬浮窗存在，更新悬浮窗中的宠物数据
    if (this.floatingWindow && this.petData.isActive) {
      this.updateFloatingPetData()
    }
  }
  
  /**
   * 更新悬浮窗中的宠物数据
   */
  updateFloatingPetData() {
    try {
      const floatingPet = this.floatingWindow.querySelector('.floating-pet')
      if (!floatingPet) return
      
      // 更新宠物表情
      const emojiElement = floatingPet.querySelector('.pet-emoji')
      if (emojiElement) {
        emojiElement.textContent = this.petData.emoji
      }
      
      // 更新宠物状态指示器
      this.updatePetStatusIndicators(floatingPet)
      
    } catch (error) {
      console.error('更新悬浮窗宠物数据失败:', error)
    }
  }
  
  /**
   * 更新宠物状态指示器
   */
  updatePetStatusIndicators(floatingPet) {
    try {
      const indicators = floatingPet.querySelector('.pet-status-indicators')
      if (!indicators) return
      
      // 清空现有指示器
      indicators.innerHTML = ''
      
      // 添加状态指示器
      if (this.petData.mood < 30) {
        const moodIndicator = document.createElement('view')
        moodIndicator.className = 'status-indicator mood-low'
        moodIndicator.title = '心情低落'
        moodIndicator.textContent = '😢'
        indicators.appendChild(moodIndicator)
      }
      
      if (this.petData.hunger < 20) {
        const hungerIndicator = document.createElement('view')
        hungerIndicator.className = 'status-indicator hunger-low'
        hungerIndicator.title = '需要喂食'
        hungerIndicator.textContent = '🍽️'
        indicators.appendChild(hungerIndicator)
      }
      
      if (this.petData.energy < 15) {
        const energyIndicator = document.createElement('view')
        energyIndicator.className = 'status-indicator energy-low'
        energyIndicator.title = '需要休息'
        energyIndicator.textContent = '😴'
        indicators.appendChild(energyIndicator)
      }
      
    } catch (error) {
      console.error('更新状态指示器失败:', error)
    }
  }
  
  /**
   * 获取悬浮窗状态
   */
  getFloatingStatus() {
    return {
      isEnabled: this.isFloatingEnabled,
      isActive: !!this.floatingWindow,
      isAppBackground: this.isAppBackground
    }
  }
  
  /**
   * 加载悬浮窗设置
   */
  loadFloatingSettings() {
    try {
      const enabled = uni.getStorageSync('floating_window_enabled')
      this.isFloatingEnabled = enabled === true
      
      console.log('悬浮窗设置已加载:', this.isFloatingEnabled)
    } catch (error) {
      console.error('加载悬浮窗设置失败:', error)
      this.isFloatingEnabled = false
    }
  }
  
  /**
   * 事件监听
   */
  on(event, callback) {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, [])
    }
    this.eventListeners.get(event).push(callback)
  }
  
  /**
   * 移除事件监听
   */
  off(event, callback) {
    if (this.eventListeners.has(event)) {
      const listeners = this.eventListeners.get(event)
      const index = listeners.indexOf(callback)
      if (index > -1) {
        listeners.splice(index, 1)
      }
    }
  }
  
  /**
   * 触发事件
   */
  emit(event, data) {
    if (this.eventListeners.has(event)) {
      this.eventListeners.get(event).forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('事件回调执行失败:', error)
        }
      })
    }
  }
  
  /**
   * 销毁管理器
   */
  destroy() {
    if (this.floatingWindow) {
      this.destroyFloatingWindow()
    }
    
    this.eventListeners.clear()
    this.isFloatingEnabled = false
  }
}

// 创建单例实例
const floatingWindowManager = new FloatingWindowManager()

export default floatingWindowManager
